package com.easondongh.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easondongh.system.domain.SysDept;
import com.easondongh.system.mapper.SysDeptMapper;
import com.easondongh.system.service.SysDeptService;
import org.springframework.util.CollectionUtils;

/**
 * @author EasonDongH
 * @date 2020/5/6 15:46
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService{

    @Autowired
    private SysDeptMapper deptMapper;

    @Override
    public List<SysDept> loadDept() {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc(SysDept.COL_ORDER_NUM);
        return this.deptMapper.selectList(queryWrapper);
    }

    @Override
    public Integer getMaxOrderNum() {
        Integer orderNum = this.deptMapper.getMaxOrderNum();
        return orderNum == null? 0: orderNum;
    }

    @Override
    public List<SysDept> getDeptExcludeById(Integer id) {
        List<SysDept> depts = this.loadDept();
        if(!CollectionUtils.isEmpty(depts)) {
            Queue<Integer> q = new LinkedList();
            q.add(id);
            while (!q.isEmpty()) {
                Integer cur = q.remove();
                // 获取cur下的所有子节点
                List<SysDept> chids = depts.stream().filter(t -> t.getPid().equals(cur)).collect(Collectors.toList());
                // 所有子节点加入队列
                chids.forEach(c -> q.add(c.getId()));
                // 从列表中移除cur节点
                depts.removeIf(d -> d.getId().equals(cur));
            }
        }
        return depts;
    }

    @Override
    public Integer countChildDeptById(Integer id) {
        return this.deptMapper.countChildDeptById(id);
    }
}
